package model

import (
	"gin_app01/utils"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"time"
)

var DEFAULT_DB *gorm.DB

//
func InitDB(sqlConfig utils.MySQLConfig) *gorm.DB {
	sqlConn := sqlConfig.Username + ":" +
		sqlConfig.Password + "@(" + sqlConfig.Host + ")/" +
		sqlConfig.DBname + "?" + sqlConfig.Config
	if db, err := gorm.Open("mysql", sqlConn); err != nil {
		log.Fatalln("数据库连接错误", err)
	} else {
		if sqlConfig.Debug {
			DEFAULT_DB = db.Debug()
		} else {
			DEFAULT_DB = db
		}
		DEFAULT_DB.DB().SetMaxIdleConns(10)
		DEFAULT_DB.DB().SetMaxOpenConns(100)
	}
	registerTable(DEFAULT_DB)
	return DEFAULT_DB
}

type Basic struct {
	ID        uint       `gorm:"primary_key" json:"id"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `sql:"index"`
}

func registerTable(db *gorm.DB) {
	db.AutoMigrate(SysUser{})
}
